<template>
  <div class="auth-container">
    <el-dialog v-model="show" center :before-close="handleClose" :show-close="false">
      <div class="auth-header">
        <h2>欢迎 ! ! !</h2>
        <p>登录或创建账号以继续</p>
      </div>

      <div class="auth-tabs">
        <button
            @click="activeTab = 'login'"
            :class="['tab', { active: activeTab === 'login' }]"
        >
          登录
        </button>
        <button
            @click="activeTab = 'register'"
            :class="['tab', { active: activeTab === 'register' }]"
        >
          注册
        </button>
      </div>

      <form @submit.prevent="handleSubmit">
        <div v-if="activeTab === 'register'" class="form-group">
          <label for="name">用户名</label>
          <input
              id="name"
              v-model="username"
              type="text"
              placeholder="4~16位的英文字母与数字"
              required
          >
        </div>

        <div v-if="activeTab === 'register' || useVerificationCode || (activeTab === 'login' && !useVerificationCode)" class="form-group">
          <label for="email">邮箱</label>
          <input
              id="email"
              v-model="email"
              type="email"
              placeholder="email@example.com"
              required
          >
        </div>

        <div v-if="activeTab === 'register' || !useVerificationCode" class="form-group">
          <label for="password">密码</label>
          <div class="password-input">
            <input v-if="activeTab === 'register'"
                   id="password"
                   :class="{ 'input-password': !showPassword }"
                   v-model="password"
                   :type="showPassword ? 'text' : 'password'"
                   placeholder="6~20位的英文字母与数字"
                   required
            >
            <input v-else
                   id="password"
                   :class="{ 'input-password': !showPassword }"
                   v-model="password"
                   :type="showPassword ? 'text' : 'password'"
                   placeholder="密码"
                   required
            >
            <button type="button" @click="togglePasswordVisibility" class="toggle-password">
              {{ showPassword ? '👁️' : '👁️‍🗨️' }}
            </button>
          </div>
        </div>

        <div v-if="activeTab === 'register'" class="form-group">
          <label for="confirmPassword">确认密码</label>
          <div class="password-input">
            <input
                id="confirmPassword"
                :class="{ 'input-password': !showConfirmPassword }"
                v-model="confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                placeholder="6~20位的英文字母与数字"
                required
            >
            <button type="button" @click="toggleConfirmPasswordVisibility" class="toggle-password">
              {{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}
            </button>
          </div>
        </div>

        <div v-if="activeTab === 'register' || useVerificationCode" class="form-group">
          <label for="verificationCode">验证码</label>
          <div class="verification-code-container">
            <input
                id="verificationCode"
                v-model="verificationCode"
                type="text"
                placeholder="输入验证码"
                :required="activeTab === 'register' || useVerificationCode"
            >
            <button
                type="button"
                @click="sendVC"
                :disabled="isCodeSending || countdown > 0"
                class="send-code-btn"
            >
              {{ buttonText }}
            </button>
          </div>
        </div>

        <div v-if="activeTab === 'login'" class="toggle-container">
          <p @click="changeLoginStyle">使用{{ loginStyle }}</p>
          <p @click="gotoRegister">还没有账号？前往注册</p>
        </div>

        <button
            @click = "submit"
            type="submit"
            :disabled="isLoading"
            class="submit-btn"
        >
          {{ submitButtonText }}
        </button>
      </form>

      <div class="auth-footer">
        <p>
          继续即表示您同意我们的服务条款和隐私政策
        </p>
      </div>

    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import {ElMessage} from "element-plus";
import {
  userLogin,
  userRegister,
  loginVerificationCode,
  registerVerificationCode
} from "@/http/m_api/user";
import appStore from "@/store";
import {storeToRefs} from "pinia";
import router from "@/router";

const activeTab = ref('login')
const isLoading = ref(false)
const isCodeSending = ref(false)
const username = ref('')
const email = ref('')
const password = ref('')
const confirmPassword = ref('')
const loginStyle = ref('验证码')
const verificationCode = ref('')
const useVerificationCode = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const countdown = ref(0)
const {createUserInfo} = appStore.useUserInfoStore
const {saveToken} = appStore.useTokenStore
// 登录
const { setUuid } = appStore.useRefreshStore;
const userInfoStore = storeToRefs(appStore.useUserInfoStore)

const show = ref(true)

const props = defineProps({
  activeTab: {
    type: String,
    default: 'login'
  },
  cancel: {
    type: Function,
    default: (fun: any) => {}
  },
  confirm: {
    type: Function,
    default: (fun: any) => {}
  }
})

const emit = defineEmits(['closeLogMod'])

activeTab.value = props.activeTab

const buttonText = computed(() => {
  if (isCodeSending.value) return '发送中...'
  if (countdown.value > 0) return `${countdown.value}s后重新发送`
  return '发送验证码'
})

const submitButtonText = computed(() => {
  if (isLoading.value) {
    return activeTab.value === 'login' ? '登录中...' : '注册中...'
  }
  return activeTab.value === 'login' ? '登录' : '注册'
})

const success = ref(false)
const handleSubmit = async () => {
  isLoading.value = true
  isLoading.value = false
  if(success === true){
    username.value = ''
    email.value = ''
    password.value = ''
    confirmPassword.value = ''
    verificationCode.value = ''
    useVerificationCode.value = false
    loginStyle.value = '验证码'
    success.value = false
  }
}

// 前端的发送验证码方法
const sendVC = async () => {
  if (email.value.length === 0) {
    ElMessage.warning('请先输入邮箱！')
    return
  }
  validateForm(email.value,  'email')
  isCodeSending.value = true
  const params = {
    email: email.value
  }
  let sendSuccess = false
  if(activeTab.value === 'register'){
    await registerVerificationCode(params).then(res => {
      if(res.code === 0) {
        ElMessage.success(`验证码已经发送到 ${email.value} ，请注意查收`)
        sendSuccess = true
      }
      else{
        ElMessage.warning(res.message)
      }
    }).catch(err => {
      ElMessage.error(err.message)
    })
  }
  else{
    await loginVerificationCode(params).then(res => {
      ElMessage.success(`验证码已经发送到 ${email.value} ，请注意查收`)
      sendSuccess = true
    }).catch(err => {
      ElMessage.error(err. message)
    })
  }
  if(sendSuccess){
    // Start the countdown
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value === 0) {
        clearInterval(timer)
      }
    }, 1000)
  }
  isCodeSending.value = false
}

const handleClose = () => {
  show.value = false;
  props.cancel();
};

// 调整密码的可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
  // console.log(showPassword.value)
}
// 调整确认密码的可见性
const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value
  // console.log(showConfirmPassword.value)
}
// 检验合法性
const validateForm = (information, type) => {
  let isValid = true;
  if (type === 'email') {
    // 简单的邮箱校验规则：包含一个@符号，并且@不能是第一个或最后一个字符
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    isValid = emailRegex.test(information);
    if(!isValid){
      ElMessage.error('邮箱格式不正确， 请确认邮箱是否正确')
    }
  } else if (type === 'username') {
    // 用户名校验规则：只包含字母数字字符，长度在4到16之间
    const usernameRegex = /^[a-zA-Z0-9]{4,16}$/;
    isValid = usernameRegex.test(information);
    if(!isValid){
      ElMessage.error('用户名不符合平台要求， 请进行修改')
    }
  } else if (type === 'password') {
    // 密码校验规则：8~20位，包含英文字母和数字
    const passwordRegex = /^[a-zA-Z\d]{6,20}$/;
    isValid = passwordRegex.test(information);
    if(!isValid){
      ElMessage.error('密码格式不正确， 请检查密码是否符合要求')
    }
  }
  else if(type === 'verificationCode'){
    // 验证码校验规则：6位数字
    const regex = /^\d{6}$/;
    isValid = regex.test(information);
    if(!isValid){
      ElMessage.error('验证码格式不正确， 请确认验证码是否正确')
    }
  }
  return isValid;
};

const changeLoginStyle = () => {
  if(loginStyle.value === '验证码'){
    loginStyle.value = '密码'
  }
  else{
    loginStyle.value = '验证码'
  }
  useVerificationCode.value = !useVerificationCode.value
}
const gotoRegister = () => {
  activeTab.value = 'register'
}

const submit = () => {
  let params;
  if (activeTab.value === 'login') {
    // 使用邮箱-验证码登录
    if(useVerificationCode.value){
      // 检验邮箱是否合法
      if(!validateForm(email.value, 'email')) {
        return;
      }
      params = {
        email: email.value,
        password: '',
        verificationCode: verificationCode.value,
        loginType: 'code',
      }
      userLogin(params).then( async res => {
        if (res.code === 0) {
          ElMessage.success("登录成功，欢迎回来！！！");
          success.value = true
          emit('closeLogMod')
          createUserInfo(res.data)
          saveToken('Bearer ' + res.data.token)
          props.confirm()
        } else {
          ElMessage.error(res.message)
        }
      }).catch(err => {
        ElMessage.error('登录异常，请稍后再试')
      })
    }
    else{
      // 检验邮箱是否合法
      if(!validateForm(email.value, 'email')) {
        return;
      }
      params = {
        email: email.value,
        password: password.value,
        verificationCode: '',
        loginType: 'password'
      }
      userLogin(params).then(async res => {
        if(res.code === 0) {
          ElMessage.success("登录成功 ， 欢迎回来！！！");
          success.value = true
          emit('closeLogMod')
          show.value = false
          createUserInfo(res.data)
          saveToken('Bearer ' + res.data.token)
          props.confirm()
        }
        else{
          ElMessage.error(res.message)
        }
      }).catch(err => {
        ElMessage.error('登录异常，请稍后再试')
      })
    }
  } else {// 注册的方法
    if (validateForm(username.value, 'username')
        && validateForm(email.value, 'email')
        && validateForm(password.value, 'password')
        && validateForm(verificationCode.value, 'VerificationCode')){
      if (password.value !== confirmPassword.value) {
        ElMessage.error('两次输入的密码不一致， 请确认密码是否正确');
        return
      }
      params = {
        "email": email.value,
        "username":username.value,
        "password":password.value,
        "verificationCode":verificationCode.value,
      }
      userRegister(params).then(async res => {
        if(res.code === 0){
          ElMessage.success("注册成功 ， 欢迎加入！！！")
          success.value = true
          emit('closeLogMod')
          show.value = false
          createUserInfo(res.data)
          saveToken('Bearer ' + res.data.token)
          props.confirm()
        }
        else{
          ElMessage.error(res.message)
        }
      }).catch(err => {
        ElMessage.error("注册异常，请稍后再试")
      })
    }
  }
}

</script>

<style lang="scss">
.auth-container {
  .el-dialog{
    width: 35vw;
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    user-select: none;
    padding: 0;

  }
  .el-dialog__header {
    display: none !important;
  }
  .el-dialog__body {
    padding: 0 !important;
  }

}
</style>

<style lang="scss" scoped>
.auth-card {
  width: 35vw;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.auth-header {
  padding: 24px;
  text-align: center;
}

.auth-header h2 {
  font-size: 24px;
  font-weight: bold;
  color: #374151;
  margin-bottom: 8px;
}

.auth-header p {
  color: #6b7280;
}

p{
  margin-bottom: 0;
}

.auth-tabs {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
}

.tab {
  flex: 1;
  padding: 12px;
  text-align: center;
  background: none;
  border: none;
  cursor: pointer;
  color: #6b7280;
  font-weight: 500;
  transition: all 0.3s;
}

.tab.active {
  color: #3b82f6;
  border-bottom: 2px solid #3b82f6;
}

form {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.form-group label {
  flex: 0 0 100px;
  font-size: 16px;
  font-weight: 500;
  color: #374151;
}

.form-group input:not([type="checkbox"]) {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.login-options {
  justify-content: flex-end;
  margin-bottom: 8px;
}

.login-options label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.login-options input[type="checkbox"] {
  margin-right: 8px;
}

.password-input {
  flex: 1;
  display: flex;
  align-items: center;
}

.password-input input {
  flex: 1;
  padding-right: 40px;
}

.input-password {
  -webkit-text-security: disc;
  -moz-text-security: disc;
  text-security: disc;
}

.input-password::-ms-reveal,
.input-password::-ms-clear {
  display: none;
}

.toggle-password {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 20px;
  padding: 0 8px;
  position: static;
  right: auto;
  display: inline-block;
  vertical-align: middle;
}

.verification-code-container {
  flex: 1;
  display: flex;
  gap: 8px;
}

.verification-code-container input {
  flex: 1;
}

.send-code-btn {
  padding: 8px 12px;
  background-color: #3b82f6;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
  white-space: nowrap;
}

.send-code-btn:hover {
  background-color: #2563eb;
}

.send-code-btn {
  &:disabled {
    background-color: #9ca3af;
    opacity: 0.5;
    cursor: not-allowed;
  }
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background-color: #3b82f6;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #2563eb;
}

.submit-btn:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.auth-footer {
  padding: 16px 24px;
  background-color: #f9fafb;
  border-top: 1px solid #e5e7eb;
  letter-spacing: 0.5px;
}

.auth-footer p {
  font-size: 12px;
  color: #6b7280;
  text-align: center;
}
.toggle-container {
  display: flex;
  justify-content: space-between;
}
.toggle-container p {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #2563eb;
  font-size: small;
  transition: color 0.3s ease; /* 添加颜色变化的过渡效果 */
}
.toggle-container p:hover {
  color: #5798fc; /* 鼠标悬停时的颜色 */
}

input::placeholder {
  font-size: 12px; /* 指定具体的字体大小 */
  color: #ccc; /* 指定placeholder的颜色 */
}

</style>

